#include "setwig.h"
#include "ui_setwig.h"
#include <QMessageBox>
#include <QDateTime>
#include <QFileDialog>
#include <QPainter>

SetWig::SetWig(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::SetWig),
    isStreaming(false),
    streamReply(0)
{
    ui->setupUi(this);

    streamUrl = "http://172.31.36.70:8080/?action=stream";

    ui->start_button->setStyleSheet("QPushButton {background: transparent;background-color: rgba(255, 255, 255, 50); color: white;}");
    ui->shot_button->setStyleSheet("QPushButton {background: transparent;background-color: rgba(255, 255, 255, 50); color: white;}");
    ui->monitor_label->setStyleSheet("QLabel{background-color: rgba(255, 255, 255, 50);border: 1px solid rgba(0, 0, 0, 30);}");
    ui->shot_label->setStyleSheet("QLabel{background-color: rgba(255, 255, 255, 50);border: 1px solid rgba(0, 0, 0, 30);}");

    ui->monitor_label->setScaledContents(false);  // 禁用自动拉伸
    ui->monitor_label->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);

    // 初始化网络管理器
    networkManager = new QNetworkAccessManager(this);
}

SetWig::~SetWig()
{
    if(streamReply) {
        streamReply->abort();
        streamReply->deleteLater();
    }
    delete ui;
}

void SetWig::on_start_button_clicked()
{
    if(isStreaming)
    {
        // 停止视频流
        if(streamReply)
        {
            streamReply->abort();
            streamReply->deleteLater();
            streamReply = 0;
        }
        ui->start_button->setText("start");
        isStreaming = false;
        ui->monitor_label->setText("视频已停止");
        ui->monitor_label->setStyleSheet("color:white;font-size: 50px;");
    }
    else
    {
        // 开始视频流
        QNetworkRequest request;
        request.setUrl(QUrl(streamUrl));

        streamReply = networkManager->get(request);
        connect(streamReply, &QNetworkReply::readyRead, this, &SetWig::handleStreamData);

        ui->start_button->setText("stop");
        isStreaming = true;
        ui->monitor_label->setText("正在连接...");
    }
}

void SetWig::handleStreamData()
{
    // 读取所有可用数据
    mjpegBuffer.append(streamReply->readAll());

    // 处理MJPEG帧
    processMjpegFrame();
}

void SetWig::processMjpegFrame()
{
    // MJPEG格式解析：查找JPEG帧开始和结束标记
    static const QByteArray jpegStartMarker = "\xff\xd8";
    static const QByteArray jpegEndMarker = "\xff\xd9";

    while(true)
    {
        int startPos = mjpegBuffer.indexOf(jpegStartMarker);
        if(startPos == -1) break;

        int endPos = mjpegBuffer.indexOf(jpegEndMarker, startPos + 2);
        if(endPos == -1) break;

        // 提取完整JPEG帧
        QByteArray jpegData = mjpegBuffer.mid(startPos, endPos - startPos + 2);
        mjpegBuffer.remove(0, endPos + 2);

        // 加载图像
        if(currentFrame.loadFromData(jpegData, "JPEG"))
        {
            // 显示在监控区域
            QPixmap pixmap = QPixmap::fromImage(currentFrame);
            pixmap = pixmap.scaled(ui->monitor_label->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
            ui->monitor_label->setPixmap(pixmap);
        }
    }
}


void SetWig::on_shot_button_clicked()
{
    if(!currentFrame.isNull())
    {
        // 在右侧标签显示
        QPixmap snapshot = QPixmap::fromImage(currentFrame)
                .scaled(ui->shot_label->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);

        // 添加时间水印
        QPainter painter(&snapshot);
        painter.setPen(Qt::white);
        painter.setFont(QFont("Arial", 12));
        painter.drawText(10, 20, QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));

        ui->shot_label->setPixmap(snapshot);

        // 保存到文件
        QString timestamp = QDateTime::currentDateTime().toString("yyyyMMdd-hhmmss");
        QString defaultName = QString("snapshot_%1.jpg").arg(timestamp);

        QString fileName = QFileDialog::getSaveFileName(this, "保存截图",defaultName,"JPEG图像 (*.jpg *.jpeg)");

        if(!fileName.isEmpty())
        {
            if(snapshot.save(fileName, "JPEG", 90))
            {
                ui->shot_label->setToolTip("已保存到: " + fileName);
            }
            else
            {
                QMessageBox::warning(this, "错误", "保存截图失败");
            }
        }
    }
    else
    {
        QMessageBox::information(this, "提示", "没有可用的图像帧");
    }
}


